using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Inspections.Commands;

/// <summary>
/// 自动点检项更新命令。
/// </summary>
/// <param name="Item"></param>
public sealed record UpdateAutoInspectionItemCommand(long Id, EquipAutoInspectionItemDto Item) : IRequest<IResult<bool>>;

internal sealed class UpdateAutoInspectionItemCommandHandler(IRepository<EquipAutoInspectionItem> repo) : IRequestHandler<UpdateAutoInspectionItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateAutoInspectionItemCommand request, CancellationToken cancellationToken)
    {
        // 点检项不能重名
        if (await repo.IsAnyAsync(m => m.PlanId == request.Item.PlanId && m.SubjectName == request.Item.SubjectName && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("点检项名称已存在");
        }

        var item = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (item == null)
        {
            return Result.Failure("未找到要更新的点检项");
        }

        item.SubjectName = request.Item.SubjectName;
        item.Symbol = request.Item.Symbol;
        item.SymbolIndex = request.Item.SymbolIndex;
        item.MinLimit = request.Item.MinLimit;
        item.MaxLimit = request.Item.MaxLimit;
        item.MeasurementUnit = request.Item.MeasurementUnit;
        item.Conversion = request.Item.Conversion;
        item.Digits = request.Item.Digits;
        item.IsCheckThreshold = request.Item.IsCheckThreshold;

        var ok = await repo.UpdateAsync(item, m => new
        {
            m.SubjectName,
            m.Symbol,
            m.SymbolIndex,
            m.MinLimit,
            m.MaxLimit,
            m.MeasurementUnit,
            m.Conversion,
            m.Digits,
            m.IsCheckThreshold,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
